package com.xiliubit.cloudpicture.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import com.xiliubit.cloudpicture.manager.auth.StpKit;
import com.xiliubit.cloudpicture.mapper.UserMapper;
import com.xiliubit.cloudpicture.model.dto.user.UserAddRequest;
import com.xiliubit.cloudpicture.model.dto.user.UserEditRequest;
import com.xiliubit.cloudpicture.model.dto.user.UserQueryRequest;
import com.xiliubit.cloudpicture.model.dto.user.UserRegisterRequest;
import com.xiliubit.cloudpicture.model.entity.User;
import com.xiliubit.cloudpicture.model.enums.UserRoleEnum;
import com.xiliubit.cloudpicture.model.vo.UserInfoVO;
import com.xiliubit.cloudpicture.model.vo.UserLoginVO;
import com.xiliubit.cloudpicture.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.xiliubit.cloudpicture.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 86173
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-07-27 20:34:23
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${defaultAvatar}")
    private String defaultAvatar;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册信息
     * @return 新用户id
     */
    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        // 获取参数
        String userAccount = userRegisterRequest.getUserAccount();
        String userName = userRegisterRequest.getUserName();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        //1.校验输入
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, checkPassword),
                ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(
                userAccount.length() < 4,
                ErrorCode.PARAMS_ERROR, "用户账号过短");
        ThrowUtils.throwIf(
                userPassword.length() < 8 || checkPassword.length() < 8,
                ErrorCode.PARAMS_ERROR, "用户密码过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword),
                ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        //2.检查是否有重复用户名
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        boolean count = this.baseMapper.exists(queryWrapper);
        ThrowUtils.throwIf(count, ErrorCode.PARAMS_ERROR, "用户名重复");
        //3.检查用户名是否为空
        if (StrUtil.isBlank(userName)) {
            userName = "无名";
        }
        // 默认头像
        String userAvatar = defaultAvatar;

        //4.加密
        String encryptPassword = getEncryptPassword(userPassword);

        //5.插入数据
        User user = User.builder()
                .userAccount(userAccount)
                .userPassword(encryptPassword)
                .userName(userName)
                .userAvatar(userAvatar)
                .userRole(UserRoleEnum.User.getValue())
                .build();
        boolean save = this.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "注册失败，系统错误");
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request      请求
     * @return 脱敏后的用户信息
     */
    @Override
    public UserLoginVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword),
                ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4,
                ErrorCode.PARAMS_ERROR, "账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8,
                ErrorCode.PARAMS_ERROR, "密码错误");
        //2.密码加密
        String encryptPassword = getEncryptPassword(userPassword);
        //3.封装数据，查找用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);

        //判断：为空则错误
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");

        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);

        // 4. 记录用户登录态到 Sa-token，便于空间鉴权时使用，注意保证该用户信息与 SpringSession 中的信息过期时间一致
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);

        // 返回结果
        return this.getLoginUser(user);
    }

    /**
     * 获取当前登录用户
     *
     * @param request 请求
     * @return 当前登录用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 获取数据
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        // 先判断是否登陆
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN_ERROR);
        // 为了确保用户数据有效，需要从数据库查询一次
        User user = this.getById(currentUser.getId());
        // 判断用户是否存在
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        return user;
    }

    /**
     * 注销用户
     *
     * @param request 请求
     * @return 用户登陆态是否移除
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 判断用户是否登录
        Object user = request.getSession().getAttribute(USER_LOGIN_STATE);
        ThrowUtils.throwIf(user == null, ErrorCode.OPERATION_ERROR,"用户未登陆");
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 用户信息修改(VO)
     * 用户修改自己的信息
     *
     * @param userEditRequest 用户信息修改请求
     * @return 修改后的用户信息
     */
    @Override
    public boolean userEdit(UserEditRequest userEditRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(userEditRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        Long id = userEditRequest.getId();
        String userName = userEditRequest.getUserName();
        String userProfile = userEditRequest.getUserProfile();
        String userPassword = userEditRequest.getUserPassword();
        String checkPassword = userEditRequest.getCheckPassword();
        // 校验权限：只有自己能修改
        ThrowUtils.throwIf(!loginUser.getId().equals(id), ErrorCode.NO_AUTH_ERROR);
        // 密码校验
        ThrowUtils.throwIf(
                userPassword.length() < 8 || checkPassword.length() < 8,
                ErrorCode.PARAMS_ERROR, "用户密码过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword),
                ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        // 构造参数
        User user = new User();
        user.setId(id);
        if (StrUtil.isNotBlank(userName)){
            user.setUserName(userName);
        }
        if (StrUtil.isNotBlank(userProfile)){
            user.setUserProfile(userProfile);
        }
        user.setUserPassword(getEncryptPassword(userPassword)); // 密码加密操作
        // 修改数据 返回结果
        return this.updateById(user);
    }

    /**
     * 管理员添加用户
     *
     * @param userAddRequest 新增用户信息
     * @return 新增用户ID
     */
    @Override
    public Long userAdd(UserAddRequest userAddRequest) {
        final String userDefaultPassword = "12345678";
        //检查是否有重复用户名
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAddRequest.getUserAccount());
        boolean count = this.baseMapper.exists(queryWrapper);
        ThrowUtils.throwIf(count, ErrorCode.PARAMS_ERROR, "用户名重复");
        //加密
        String encryptPassword = getEncryptPassword(userDefaultPassword);
        // 插入数据
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        user.setUserPassword(encryptPassword);
        boolean result = this.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回用户信息
        return user.getId();
    }

    /**
     * 获取用户信息
     *
     * @param id 用户id
     * @return 脱敏后的用户信息
     */
    @Override
    public UserInfoVO getUserById(Long id) {
        User user = this.getById(id);
        return getUserInfo(user);
    }

    /**
     * 获取脱敏后的用户
     *
     * @param user 用户
     * @return 脱敏后的用户
     */
    @Override
    public UserInfoVO getUserInfo(User user) {
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        return userInfoVO;
    }

    /**
     * 获取脱敏后的用户列表
     *
     * @param  userList 未脱敏的用户列表
     * @return 脱敏后的用户列表
     */
    @Override
    public List<UserInfoVO> getUserVOList(List<User> userList) {
        ThrowUtils.throwIf(userList == null, ErrorCode.PARAMS_ERROR);
        return userList.stream().map(this::getUserInfo).collect(Collectors.toList());
    }


    /**
     * 对登录用户脱敏
     *
     * @param user 当前用户
     * @return 脱敏后的用户信息
     */
    @Override
    public UserLoginVO getLoginUser(User user) {
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        return userLoginVO;
    }

    /**
     * 获取查询条件
     *
     * @param userQueryRequest 用户查询条件
     * @return 查询条件
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);

        // 组装sql查询语句
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StringUtils.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StringUtils.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),sortOrder.equals(UserQueryRequest.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }



    /**
     * 判断是否为管理员
     *
     * @param user 登陆用户
     * @return 是否为管理员
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.Admin.getValue().equals(user.getUserRole());
    }

    /**
     *  获取加密密码
     * @param userPassword 密码
     * @return 加密后的密码
     */
    private String getEncryptPassword(String userPassword) {
        // 加盐，混淆密码
        final String salt = "xiliubit";
        return DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());
    }
}




